<?php
declare (strict_types = 1);

namespace app\api\library;

use app\api\model\UserCredit;
use app\api\model\UserCreditLog;

class Credit
{

    /**
     * 增加积分
     * param $uk ，存在时要进行判断，比如月结一次的计算
     */
    public static function addIntergral($uid, $num, $type, $uk = null)
    {
        $return = false;       
        if ($num !=0) {
            $saveAble = 1;
            if ($uk) {
                $f              = UserCreditLog::where('u_id', $uid)->where('type',$type)->where('uk', $uk)->find();
                $f && $saveAble = 0;

            }
       
         
            if ($saveAble == 1) {
 
               $r =  UserCreditLog::create([
                    'u_id'     => $uid,
                    'integral' => $num,
                    'type'     => $type,
                    'uk'       => $uk,
                ]);

                $return = true;
                $t      = UserCredit::where('u_id',$uid)->find();                
                if ($t && !$t->isEmpty()) {
                    $t->integral = $t->integral + $num;
                    $t->level    = self::updateLevel($t->integral + $num);
                    $t->save();
                } else {
                    UserCredit::create([
                        'u_id'     => $uid,
                        'integral' => $num,
                        'level'    => 1,
                    ]);
                }

            }

        }

        return $return;

    }

    public static function updateLevel($fen)
    {
        $newLevel = 1;
        $levels   = UserCredit::creditLevel();
        foreach ($levels as $k => $v) {
            $rule = explode(',', $v[1]);
            if ($fen > $rule[0]) {
                $newLevel = $k;
            }
        }
        return $newLevel;
    }


    /**
     * 信用分添加接口
     * @param  [type] $uid   [description]
     * @param  [type] $scene [description]
     * @return [type]        [description]
     */
    public static function sceneLog($uid, $scene,$ext=[])
    {
        $cfg = getConfig("credit");
        if(!$cfg){
            return false;
        }
        $num = $cfg[$scene];
        $uk= null;
        switch ($scene) {
            //根据充值金额调整
            case 'recharge':
                $num = $num*$ext['total'];
                $uk = $ext['uk'];
                break;      //根据充值金额调整
            case 'profile_truename':
            case 'profile_mobile':
            case 'profile_complete':
            case 'profile_email_vetify':
            case 'mission_pub10':          
                $uk = $scene;
                break;     
            default:         
                $uk = $ext['uk'];
                break;        
        }
      
        return self::addIntergral($uid, $num, $scene, $uk);
    }

}
